package com.hex.campus.backend.hex_campus_backend.controller;

import com.hex.campus.backend.hex_campus_backend.entity.Partner;
import com.hex.campus.backend.hex_campus_backend.entity.PartnerMatch;
import com.hex.campus.backend.hex_campus_backend.service.PartnerService;
import com.hex.campus.backend.hex_campus_backend.util.JwtUtil;
import jakarta.persistence.EntityNotFoundException;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/partners")
@RequiredArgsConstructor
public class PartnerController {
    private final PartnerService partnerService;
    private final JwtUtil jwtUtil;

    @PostMapping
    public ResponseEntity<?> createPartner(
            @RequestBody Partner partner,
            @RequestHeader("Authorization") String token) {

        try {
            Long userId = jwtUtil.validateToken(token.replace("Bearer ", ""));
            // 检查必填字段是否为空
            if (partner.getTitle() == null || partner.getDescription() == null || partner.getSubject() == null || partner.getPreferredTime() == null || partner.getContactMethod() == null) {
                throw new IllegalArgumentException("请填写完整信息，包括标题、描述、主题、时间和联系方式");
            }
            Partner createdPartner = partnerService.createPartner(partner, userId);

            // 添加日志记录
            System.out.println("帖子创建成功，ID: " + createdPartner.getId());

            // 返回完整的 Partner 对象
            return ResponseEntity.ok(createdPartner);
        } catch (IllegalArgumentException e) {
            // 捕获非法参数异常并返回详细的错误信息
            Map<String, String> error = new HashMap<>();
            error.put("message", e.getMessage());
            return ResponseEntity.badRequest().body(error);
        } catch (Exception e) {
            // 添加日志记录，便于排查问题
            System.err.println("创建帖子失败: " + e.getMessage());
            Map<String, String> error = new HashMap<>();
            error.put("message", "服务器内部错误，请稍后重试");
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(error);
        }
    }

    @GetMapping
    public ResponseEntity<Page<Partner>> getPartners(
            @RequestParam(required = false) String subject,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {

        Pageable pageable = PageRequest.of(page, size, Sort.by("createdAt").descending());
        return ResponseEntity.ok(partnerService.getPartners(pageable, subject));
    }

    @PostMapping("/{id}/matches")
    public ResponseEntity<PartnerMatch> createMatch(
            @PathVariable Long id,
            @RequestHeader("Authorization") String token) {

        Long userId = jwtUtil.validateToken(token.replace("Bearer ", ""));
        return ResponseEntity.ok(partnerService.createMatch(id, userId));
    }

    @RestControllerAdvice
    public class GlobalExceptionHandler {

        // 捕获所有 IllegalArgumentException
        @ExceptionHandler(IllegalArgumentException.class)
        public ResponseEntity<Map<String, String>> handleIllegalArgumentException(IllegalArgumentException ex) {
            Map<String, String> error = new HashMap<>();
            error.put("message", ex.getMessage());
            return ResponseEntity.badRequest().body(error);
        }

        // 捕获 EntityNotFoundException
        @ExceptionHandler(EntityNotFoundException.class)
        public ResponseEntity<Map<String, String>> handleEntityNotFoundException(EntityNotFoundException ex) {
            Map<String, String> error = new HashMap<>();
            error.put("message", ex.getMessage());
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(error);
        }
    }

    @GetMapping("/{id}")
    public ResponseEntity<?> getPartnerById(@PathVariable Long id) {
        try {
            Partner partner = partnerService.getPartnerById(id);
            return ResponseEntity.ok(partner);
        } catch (EntityNotFoundException e) {
            Map<String, String> error = new HashMap<>();
            error.put("message", "找不到该帖子");
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body(error);
        }
    }
}